define([
    'lodash',
    'visit-plan/status-bar',
    'visit-plan/plan-sidebar',
    'api',
], function (_, StatusBar, PlanSidebar, api) {
    var sysDate = new Date();
    var PlanTable = {
        name: 'plan-table',
        template: ''
        + '<div class="plan-table-wrapper">'
        + '<div class="plan-table-container">'
        + '<div class="change-wrapper">'
        + '<span  @click="handleMoveMonth(-1)" class="arrow-left"></span>'
        + '<i-select v-model="currentSelectDate" size="small" style="width: 120px;" @on-change="handleChange">'
        + '<i-option v-for="item in optionData" :value="item.value" :key="item.value">{{ item.label }}</i-option>'
        + '</i-select>'
        + '<span @click="handleMoveMonth(1)" class="arrow-right"></span>'
        + '</div>'
        + '<table class="plan-table">'
        + '<thead>'
        + '<tr>'
        + '<th>周一</th>'
        + '<th>周二</th>'
        + '<th>周三</th>'
        + '<th>周四</th>'
        + '<th>周五</th>'
        + '<th>周六</th>'
        + '<th>周日</th>'
        + '</tr>'
        + '</thead>'
        + '<tbody>'
        + '<tr v-for="row in daysData">'
        + '<td v-for="col in row" @click="handleChangeSidebarPlanData(col)" :class="{ dimmed: col.isDimmed }">'
        + '<div class="date-text" :class="{ today: col.isToday }">'
        + '<span>{{ col.val }}</span>'
        + '</div>'
        + '<div class="status-bar-scroller">'
        + '<div class="status-bar-container">'
        + '<div class="status-bar-wrapper">'
        + '<status-bar v-for="(item, index) in formatDayPlanTotal(col)" :type="item.type" :status="item.status" :key="index">{{ item.name + item.count }}</status-bar>'
        + '</div>'
        + '</div>'
        + '</div>'
        + '</td>'
        + '</tr>'
        + '</tbody>'
        + '</table>'
        + '</div>'
        + '<plan-sidebar :plan-data="selectedDayPlanData" :month-total="formatMonthPlanTotal" :date="currentSelectDate"></plan-sidebar>'
        + '</div>',
        components: {
            StatusBar: StatusBar,
            PlanSidebar: PlanSidebar
        },
        props: {
            yearULV: {
                type: Number,
                default: sysDate.getFullYear()
            },
            yearDLV: {
                type: Number,
                default: sysDate.getFullYear() - 2
            }
            // planData: {
            //   type: Array,
            //   default: function () {
            //     return [];
            //   }
            // }
        },

        data: function () {
            return {
                sysDate: sysDate,
                nowDate: sysDate,
                nowYear: sysDate.getFullYear(),
                nowMonth: sysDate.getMonth() + 1,
                currentSelectDate: '',
                checkedDate: null,
                daysData: [],
                optionData: [],
                currMonthPlanData: [],
                selectedDayPlanData: {}
            }
        },

        computed: {
            formatMonthPlanTotal: function () {
                return _.chain(this.currMonthPlanData)
                    .map(function (val) {
                        return val.item;
                    })
                    .flatten()
                    .countBy('status')
                    .value();
            },
        },

        created: function () {
            this.init();
        },

        methods: {
            init: function () {
                this.initSelectData();
                this.currentSelectDate = this.nowYear + '-' + this.nowMonth;
                this.createDaysData(this.nowDate);
            },

            initSelectData: function () {
                for (var year = this.yearDLV; year <= this.yearULV; year++) {
                    for (var month = 1; month <= 12; month++) {
                        this.optionData.push({
                            label: year + '年' + month + '月',
                            value: year + '-' + month
                        });
                    }
                }
            },

            isToday: function (dayData) {
                var sysYear = this.sysDate.getFullYear();
                var sysMonth = this.sysDate.getMonth() + 1;
                var sysDay = this.sysDate.getDate();

                if (sysYear === this.nowYear && sysMonth === this.nowMonth && sysDay === dayData.val && !dayData.isDimmed) {
                    return true;
                }
            },

            // 设置当前时间
            setNowDate: function (paramNowDate) {

                var tempYear = paramNowDate.getFullYear();

                // 如果新传入的nowDate对象年份大于指定的上限值或小于指定的下限值该函数不执行
                if (tempYear > this.yearULV || tempYear < this.yearDLV) {
                    return false;
                }

                this.nowDate = paramNowDate;
                this.nowYear = tempYear;
                this.nowMonth = this.nowDate.getMonth() + 1;

            },

            formatDayPlanTotal: function (data) {
                var planItems = data.hasOwnProperty('planItem') ? data.planItem : [];
                var isToday = data.isToday;
                var formatted = [];
                var flagPush = true;

                for (var i = 0; i < planItems.length; i++) {
                    for (var j = 0; j < formatted.length; j++) {
                        var where = isToday
                            ? planItems[i].name === formatted[j].name && planItems[i].status === formatted[j].status && planItems[i].type && formatted[j].type
                            : planItems[i].name === formatted[j].name && planItems[i].status === formatted[j].status;
                        if (where) {
                            formatted[j].count++;
                            flagPush = false;
                        }
                    }
                    if (flagPush) {
                        formatted.push({
                            name: planItems[i].name,
                            type: isToday ? planItems[i].type : planItems[i].status,
                            status: planItems[i].status,
                            count: 1
                        })
                    } else {
                        // reset flag
                        flagPush = true;
                    }
                }

                return formatted;
            },

            formatDaysDate: function (daysArray) {
                var formatted = [];
                var item = [];

                for (var i = 0; i < daysArray.length; i++) {
                    // 如果是今天添加isToday字段
                    if (this.isToday(daysArray[i])) {
                        daysArray[i].isToday = true;
                    }
                    // 添加计划字段
                    for (var k = 0; k < this.currMonthPlanData.length; k++) {
                        if (daysArray[i].val === this.currMonthPlanData[k].day && !daysArray[i].isDimmed) {
                            daysArray[i].planItem = this.currMonthPlanData[k].item;
                        }
                    }

                    item.push(daysArray[i]);
                    if ((i + 1) % 7 === 0) {
                        formatted.push(item);
                        item = [];
                    }
                }

                return formatted;
            },

            // 生成月份天数数据数组
            createDaysData: function (dateObj) {
                var
                    // 当月的天数
                    nowDays = this.getDays(this.nowYear, this.nowMonth),

                    // 上个月的天数
                    lastDays = this.getDays(this.nowYear, this.nowMonth - 1),

                    // 保存这个月第一天是星期几
                    whatDay = new Date(this.nowYear, this.nowMonth - 1, 1).getDay(),

                    // 保存上月末尾的天数总和
                    lastDaysEnd = 6 - (7 - whatDay),

                    // 生成的天数数据数组
                    daysArray = [],

                    // 保存上个月末尾天数的起始天数
                    startLastDaysEnd = lastDays - lastDaysEnd,

                    i;


                // 产生上月末尾的天数
                // dimmed: 表示上月以及下月不可用的日期
                for (i = 0; i < lastDaysEnd; i++) {
                    // daysArray[i] ='dimmed-' + (startLastDaysEnd + i + 1);
                    daysArray[i] = {
                        isDimmed: true,
                        val: (startLastDaysEnd + i + 1)
                    }
                }

                // 产生本月的天数
                for (i = 1; i <= nowDays; i++) {
                    // daysArray.push('normal-' + i);
                    daysArray.push({
                        isDimmed: false,
                        val: i
                    })
                }

                // 产生余下的下月天数
                for (i = 1; daysArray.length < 38; i++) {
                    // daysArray.push('dimmed-' + i);
                    daysArray.push({
                        isDimmed: true,
                        val: i
                    })
                }

                var that = this;
                api.fetchPlanData({month: this.currentSelectDate})
                    .done(function (res) {
                        if (res.IsSuccess) {
                            that.currMonthPlanData = res.ResultObject;
                        }
                    })
                    .fail(function () {
                        that.currMonthPlanData = [];
                    })
                    .always(function () {
                        that.daysData = that.formatDaysDate(daysArray);
                    });

            },

            // 获取某个月共有几天
            getDays: function (year, month) {
                var days;
                // 当月份为二月时，根据闰年还是非闰年判断天数
                if (month === 2) {
                    days = year % 4 === 0 ? 29 : 28;

                } else if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) {
                    // 月份为：1,3,5,7,8,10,12 时，为大月.则天数为31；
                    days = 31;
                }
                else {
                    // 其他月份，天数为：30.
                    days = 30;
                }

                return days;
            },

            handleChange: function (val) {
                this.setNowDate(new Date(val));
                this.createDaysData(this.nowDate);
            },

            handleChangeSidebarPlanData: function (col) {
                if (col.isDimmed) return false;
                this.selectedDayPlanData = col;
            },

            handleMoveMonth: function (offset) {
                this.setNowDate(new Date(this.nowYear, this.nowMonth - 1 + offset));
                this.createDaysData(this.nowDate);
                this.currentSelectDate = this.nowYear + '-' + this.nowMonth;
            }
        }
    }

    return PlanTable;
});

